package com.xhwl.centiotdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.centiotdata.dao.RepairScopeConfigMapper;
import com.xhwl.centiotdata.service.RepairScopeConfigService;
import com.xhwl.common.dto.cent.iotdata.repair.RepairActionDTO;
import com.xhwl.common.pojo.cent.iot.RepairScopeConfig;
import com.xhwl.common.utils.CalendarUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright (C),1998-2022, 兴海物联
 * FileName: RepairDetailLogService
 * Author: XuChang
 * Date: 2022/5/27 11:02
 * Description: 可修复范围配置
 * History:
 */
@Service
public class RepairScopeConfigServiceImpl extends ServiceImpl<RepairScopeConfigMapper, RepairScopeConfig>
        implements RepairScopeConfigService {

    @Override
    public List<RepairScopeConfig> getConfig(Integer projectId) {
        return getBaseMapper().selectList(new LambdaQueryWrapper<RepairScopeConfig>().eq(RepairScopeConfig::getProjectId, projectId));
    }

    @Override
    public boolean isLegalScope(RepairActionDTO repairActionDTO) {
        if (repairActionDTO == null)
            return false;
        List<RepairScopeConfig> config = getConfig(repairActionDTO.getProjectId());
        if (CollectionUtils.isEmpty(config))
            return false;
        List<RepairScopeConfig> collect = config.stream().filter(repairScopeConfig -> repairActionDTO.getOperateType() == repairScopeConfig.getRepairType())
                .filter(repairScopeConfig -> before(repairScopeConfig.getBeginTime(), format(repairActionDTO.getStartDate()))
                        && before(format(repairActionDTO.getEndDate()), getEndTime(repairScopeConfig.getEndTime())))
                .collect(Collectors.toList());
        return !collect.isEmpty();
    }

    /**
     * 如果endTime未配置，则取昨日
     *
     * @param endTime
     * @return
     */
    private Date getEndTime(Date endTime) {
        if (endTime == null) {
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.DAY_OF_YEAR, -1);
            endTime = instance.getTime();
        }
        return endTime;
    }

    /**
     * 日期是否在之前，同一天也可以
     *
     * @param dateF
     * @param dateS
     * @return
     */
    private boolean before(Date dateF, Date dateS) {
        return dateF.before(dateS) || CalendarUtil.isOneDay(dateF, dateS);
    }

    private Date format(String dateStr) {
        try {
            Date date = CalendarUtil.getDate(CalendarUtil.DATE_FORMAT[1], dateStr);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

}




